<template>
  <div id="import">
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/' }" style="padding-left: 10px;">系统首页</el-breadcrumb-item>
      <el-breadcrumb-item><b>基础数据维护</b></el-breadcrumb-item>
    </el-breadcrumb>
    <el-row>
      <el-col :style="mystyle">
        <el-form>
        <h1>基础数据维护</h1>
          <el-button @click="datadownload()" icon="el-icon-download" type="success">补充数据下载</el-button>
          <el-upload class="upload-demo" :before-upload="beforeAvatarUpload" :on-success="getImportList" name="file" :file-list="fileList"
              :action="this.$http.defaults.baseURL + 'admin/binfo/upload'" with-credentials accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" :on-error='uploaderror' style="margin-top:20px">
            <el-button type="primary" icon="el-icon-document">补充数据上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传xls/xls文件</div>
          </el-upload>
          <hr>
        </el-form>
        <h1>
          管理员维护
        </h1>
        <el-dialog title="设置用户姓名" :visible.sync="showRealnameModal" width="30%">
          <el-form ref="truenameForm" :model="currentUser" :rules="truenameRules" label-width="80px">
            <el-form-item label="姓名" prop="truename">
              <el-input v-model="currentUser.truename"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="showRealnameModal = false">取消</el-button>
            <el-button type="primary" @click="saveRealname" :loading="loading">保存</el-button>
          </div>
        </el-dialog>
        <el-dialog title="重置密码" :visible.sync="showPasswordModal" width="30%">
          <el-form ref="passwordForm" :model="modPasswordForm" :rules="passwordRules" label-width="80px">
            <el-form-item label="用户名" prop="username">
              {{ modPasswordForm.username }}
            </el-form-item>
            <el-form-item label="密码" prop="NewPassword">
              <el-input type="password" v-model="modPasswordForm.NewPassword" auto-complete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="showPasswordModal = false">取消</el-button>
            <el-button type="primary" @click="savePassword" :loading="loading">保存</el-button>
          </div>
        </el-dialog>
        <el-table :data="userData" id="admin-user-table" border v-loading="loading">
          <el-table-column label="用户类型" prop="userType" width="250" align="center"></el-table-column>
          <el-table-column label="用户名" prop="username" width="250" align="center"></el-table-column>
          <el-table-column label="姓名" prop="truename" width="250" align="center"></el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="primary" style="margin:10px" @click="openRealnameModal(scope.row)">设置用户姓名</el-button>
              <el-button type="success" style="margin:10px" @click="openPasswordModal(scope.row)" v-if="scope.row.userType !== '系统管理员'">重置密码</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- <el-select v-model="theyear" placeholder="请选择年份">
          <el-option
            v-for="item in years"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
        <el-button @click="shhdata()" icon="el-icon-upload2" type="primary" :loading="shhloading" style="margin-top:20px">导入部直属单位数据（从民主生活会）</el-button> -->
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  data () {
    var validatePassword = (rule, value, callback) => {
      // 密码规则校验
      var num = 0
      var rule1 = /\d+/
      var rule2 = /[a-z]+/
      var rule3 = /[A-Z]+/
      var rule5 = /^.{10,32}$/
      var ruleAll = /^[a-zA-Z0-9]+$/
      var flag1 = rule1.test(value)
      var flag2 = rule2.test(value)
      var flag3 = rule3.test(value)
      var flag5 = rule5.test(value)
      if (flag1) {
        num = num + 1
      }
      if (flag2) {
        num = num + 1
      }
      if (flag3) {
        num = num + 1
      }
      if (!rule5.test(value)) {
        callback(new Error('密码长度必须是10位及以上，32位以下！'))
      }
      if (!ruleAll.test(value)) {
        callback(new Error('密码不能包含特殊字符！'))
      }
      if (!(num > 1 && flag5)) {
        callback(new Error('密码必须是10位及以上数字、大、小写字母中的两种及两种以上的组合，不含特殊字符！'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      userTemplate: [
        { id: 1, userType: '系统管理员', username: 'admin_sys' },
        { id: 2, userType: '安全审计员', username: 'admin_audit' },
        { id: 3, userType: '授权管理员', username: 'admin_right' }
      ],
      userData: [],
      fileList: [],
      mystyle: 'background:#fff;border-radius:5px;margin:0 20px; padding:0 20px;width: calc(100% - 20px);height:' + 500 + 'px',
      shhloading: false,
      years: [],
      theyear: '',
      showRealnameModal: false,
      showPasswordModal: false,
      currentUser: {},
      // 表单验证规则
      truenameRules: {
        truename: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ]
      },
      passwordRules: {
        NewPassword: [
          { validator: validatePassword, trigger: 'blur' }
        ]
      },
      modPasswordForm: {username: '', NewPassword: '', userId: ''}
    }
  },
  methods: {
    getUserData () {
      // let usernameList = [
      //   {username: 'admin_sys', truename: '张三1111'},
      //   {username: 'admin_audit', truename: '李四2222'},
      //   {username: 'admin_right', truename: '王五3333'}
      // ]
      // this.userData.forEach(item => {
      //   item.truename = usernameList.find(user => user.username === item.username).truename
      // })
      this.userData = []
      this.loading = true
      this.$http.get('/admin/getAdminList/').then((response) => {
        this.loading = false
        console.log('response.data')
        console.log(response.data)
        let usernameList = response.data
        let userTemplate = JSON.parse(JSON.stringify(this.userTemplate))
        userTemplate.forEach(item => {
          item.truename = usernameList.find(user => user.username === item.username).truename
          console.log('item.truename')
          console.log(item.truename)
        })
        this.userData = userTemplate
        console.log('this.userData')
        console.log(this.userData)
      })
    },
    openRealnameModal (row) {
      // 深拷贝当前行数据，避免直接修改表格数据
      this.currentUser = { ...row }
      this.showRealnameModal = true
    },
    openPasswordModal (row) {
      // 深拷贝当前行数据，避免直接修改表格数据
      this.modPasswordForm.username = row.username
      this.modPasswordForm.userId = row.id
      this.showPasswordModal = true
      this.modPasswordForm.NewPassword = ''
    },
    savePassword () {
      // 表单验证
      this.$refs.passwordForm.validate((valid) => {
        if (valid) {
          this.loading = true
          let para = {
            username: this.modPasswordForm.username,
            password: this.modPasswordForm.NewPassword
          }
          this.loading = true
          this.$http.post(`/admin/adminPassword/`, para).then((response) => {
            if (response.data.IsSuccess === true) {
              this.$message({
                message: '重置密码成功',
                type: 'success'
              })
              this.showPasswordModal = false
            } else {
              console.log('重置密码失败:' + response.data.Msg)
              this.$message({
                message: '重置密码失败:' + response.data.Msg,
                type: 'error'
              })
            }
            this.loading = false
          })
        }
      })
    },
    // 保存用户名
    saveRealname () {
      // 表单验证
      this.$refs.truenameForm.validate((valid) => {
        if (valid) {
          this.loading = true
          let para = {
            username: this.currentUser.username,
            truename: this.currentUser.truename
          }
          this.loading = true
          this.$http.post(`/admin/adminTruename/`, para).then((response) => {
            if (response.data.IsSuccess === true) {
              this.$message({
                message: '设置成功',
                type: 'success'
              })
              this.showRealnameModal = false
              this.getUserData()
            } else {
              console.log('设置失败:' + response.data.Msg)
              this.$message({
                message: '设置失败:' + response.data.Msg,
                type: 'error'
              })
            }
            this.loading = false
          })
        }
      })
    },
    beforeAvatarUpload (file) {
      console.log('文件类型')
      console.log(file.name)
      const isXLS = file.name.indexOf('.xls') > 0
      const isXLSX = file.name.indexOf('.xlsx') > 0
      // const isLt5M = file.size / 1024 / 1024 < 500
      if (!isXLS && !isXLSX) {
        this.$message.error('上传文件只能是 xls/xlsx 格式!')
      }
      // if (!isLt5M) {
      //   this.$message.error('上传文件大小不能超过 500MB!')
      // }
      // return isZIP && isLt5M
      return isXLS || isXLSX
    },
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    handlePreview (file) {
      console.log(file)
    },
    handleExceed (files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，如有多个文件请压缩为zip文件打包上传。`)
    },
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleCurrentChange (val) {
      this.pageNum = val
      this.getImportList()
    },
    importPersons () {
      this.getImportList()
    },
    // 获取用户列表
    getImportList (res) {
      if (res.success) {
        this.$message({
          message: '导入成功！' + res.message,
          type: 'success'
        })
      } else {
        console.log(res.Msg)
        this.$message({
          message: '导入失败:' + res.message,
          type: 'error'
        })
      }
      this.fileList = []
    },
    mainheight (obj) {
      var clientHeight = 0
      if (document.body.clientHeight && document.documentElement.clientHeight) {
        clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight
      } else {
        clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight
      }
      obj.mystyle = 'background:#fff;border-radius:5px;margin:0 20px; padding:0 20px;width: calc(100% - 20px);height:' + (clientHeight - 150) + 'px'
    },
    uploaderror (err) {
      console.log('具体错误')
      console.log(err)
      this.$message({
        message: '导入失败，可能是文件大小超出系统限制:' + err,
        type: 'error'
      })
    },
    datadownload (id) {
      window.open(this.$http.defaults.baseURL + 'admin/binfo/download')
    },
    shhdata () {
      var _this = this
      this.$confirm('确定从民主生活会导入部直属单位相关数据?', '提示', {
        type: 'success'
      }).then(() => {
        let para = {theyear: this.theyear}
        this.shhloading = true
        this.$http.post(`/admin/initfromshh/`, para).then(function (response) {
          if (response.data.success === true) {
            _this.$message({
              message: '导入成功',
              type: 'success'
            })
          } else {
            console.log('导入失败:' + response.data.message)
            _this.$message({
              message: '导入失败:' + response.data.message,
              type: 'error'
            })
          }
          _this.shhloading = false
        })
      }).catch(function () {
      })
    },
    setyears () {
      let date = new Date()
      let firstyear = date.getFullYear() - 3
      for (var i = 0; i <= 6; i++) { this.years[i] = firstyear + i }
      this.theyear = firstyear + 2
    }
  },
  mounted () {
    this.getUserData()
    this.setyears()
    this.mainheight(this)
    let _this = this
    window.onresize = function windowResize () {
      // 通过捕获系统的onresize事件触发我们需要执行的事件
      _this.mainheight(_this)
    }
  }
}
</script>
<style scope>
#import .el-upload-list__item{
  width: 250px;
}
#import a{
  width: 200px;
}
#admin-user-table{
  width: 100%;
  border: #95B8E7 solid 1px;
}
#admin-user-table th{
    font-weight: normal;
    background-image: linear-gradient(to bottom , #f8f8f8, #efefef);
    text-align: center;
    border-right: #95B8E7 solid 1px;
    border-bottom: #95B8E7 solid 1px;
    min-height: 30px;
    line-height:30px;
  }
  #admin-user-table td{
    padding:0;
    font-size:var(--size14) !important;
    line-height: 20px;
    font-family: '宋体',
  }
</style>
